package pers.cocoadel.springcloud.loadBalance;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author rwby
 */
@Component
public class LoadBalancerImpl implements LoadBalancer
{

    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    private int getAndIncrement()
    {
        int currentIndex;
        int index;
        do
        {
            currentIndex = atomicInteger.get();
            index = currentIndex == 0x7ffffff ? 0 : currentIndex + 1;
        }
        while (!atomicInteger.compareAndSet(currentIndex, index));
        return index;
    }

    @Override
    public ServiceInstance getServiceInstance(List<ServiceInstance> serviceInstances)
    {
        if (CollectionUtils.isEmpty(serviceInstances))
        {
            return null;
        }

        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}
